<?php
/**
 * 团购任务
 */
class TuanAction extends Action {
	/**
	 * [tuanTask 定时任务入口]
	 * @return [type] [description]
	 */
	public function tuanTask(){
		self::tuanRefund();
	}
	/**
	 * [tuanRefund 团购退款]
	 * @return [type] [description]
	 */
	public function tuanRefund(){
		Session::switchCustomer(0);
		$OrderModel=M("module_product_order");
		$teamOrder = M("module_team_order");
		$time =time();
		$str="SELECT a.id AS teamId,b.teamEndTime,a.createTime,d.id,c.status,c.id AS oid,c.price,c.fromUserName,c.fromCustomerId"
  			." FROM wx_module_team_order a"
			." INNER JOIN wx_module_product b ON a.pid=b.id"
			." INNER JOIN wx_module_team_order_detail d ON d.teamId=a.id"
			." INNER JOIN wx_module_product_order c ON c.id=d.oid"
			." WHERE a.status < 1 AND (c.status='teaming')";

		$orderList=$OrderModel->query($str);
		$time=time();
		foreach ($orderList as $key => $value) {
			$customerId=$value["fromCustomerId"];
			$_GET["customerId"]=$customerId;
			$toUser=$value["fromUserName"];
			if($value["teamEndTime"]) {
				$teamEndTime=strtotime($value["teamEndTime"]);
				$oid=$value["oid"];
				$price=$value["price"];
				if($time > $teamEndTime) {
					$out=R('Product/orderRefund', array($oid,$price));
					$data['status'] = '3';
					$data['updateTime'] = date('Y-m-d H:i:s',time());
					$condition['id']=array("eq",$value['teamId']);
					$teamOrder->where($condition)->save($data);
				}
			}
		}
	}

	public function tuanBackMoney($oid){
		Session::switchCustomer(0);
		$teamOrder = M("module_team_order");
		$teamOrderDetail = M("module_team_order_detail");
		$teamOrderList = $teamOrder->alias("a")
			->join("inner join wx_module_team_order_detail b on a.id = b.teamId")
			->join("inner join wx_module_product_order c on c.id = b.oid")
			->join("inner join wx_module_product_order_detail e on c.id=e.oid")
			->where("c.id = $oid and a.openBack=1 and a.status > 0 and a.isBack = '0' and (c.status = 'teaming' or c.status = 'ok')")
			->field("a.id,c.isTeam,a.teamCount,a.backMoney,c.fromCustomerId,b.oid,b.fromUserName,e.count")
			->group("a.id")->find();
		$customerId=$teamOrderList["fromCustomerId"];
		$_GET["customerId"]=$customerId;
		Session::switchCustomer($customerId);
		if(!$teamOrderList){
			return;
		}
		$id= $teamOrderList['id'];
		$teamCount = $teamOrderDetail
			->alias("a")
			->join("wx_module_product_order as b on a.oid = b.id")
			->where("(b.status='ok') and a.teamId=".$id)
			->count();
		if($teamCount>=$teamOrderList['teamCount']){
			$arr = $teamOrderDetail->alias("a")
				->join("inner join wx_module_product_order b on a.oid = b.id")
				->join("inner join wx_module_product_order_detail c on b.id=c.oid")
				->where("a.teamId=".$teamOrderList['id']." and a.role=1")
				->field("a.oid,b.price,c.count")->find();
			$oid = $arr["oid"];
			$backMoney = $teamOrderList["backMoney"]*$arr['count'];
			//订单方式
			$condition["id"] = array("eq",$teamOrderList['id']);
			$data["isBack"]=1;
			$data['updateTime'] = date('Y-m-d H:i:s');
			$teamOrder->where($condition)->save($data);
			$out=R('Product/orderRefund', array($oid,$backMoney));
			//红包方式
//			$arr = $teamOrderDetail->where("teamId=".$teamOrderList['id']." and role=1")
//				->field("fromUserName")->find();
//			$fromUserName = $arr['fromUserName'];
//
//			$payCode=WeixinApi::sendRedEnvelopeByOpenId(
//				"密友圈商城",
//				$fromUserName,
//				$backMoney,
//				"组团成功！犒劳团长，大红包一个！",
//				false,
//				$setting["payKey"],
//				$setting["mchId"],
//				$setting["appId"]
//			);
//			if($payCode) {
//				self::SendorderNotice($teamOrderList['oid']);

//			}
		}
	}
	public static function SendorderNotice($oid){
		$cid = Session::$user["customerId"];
		$TemplateModel = M("template_messages");
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		Session::switchCustomer($cid);
		$where['a.id'] = $oid;
		$order = $OrderModel->alias("a")
			->join("inner join wx_".$cid."_user_weixin_info b on a.fromUserName=b.openid")
			->join("inner join wx_module_product_order_detail c on a.id = c.oid")
			->join("inner join wx_module_product d on c.pid = d.id")
			->field("a.*,b.nickname,d.teamBackMoney")
			->where($where)->find();

		$twhere['status'] = "teamBackNotice";
		$templatemsg = $TemplateModel->where($twhere)->find();
		$templateId = $templatemsg['templateId'];
		$data['first'] = array('value'=> '亲，你发起的组团购返现成功。','color'=>"#743A3A");
		$data['keyword1'] = array('value'=> $order["teamBackMoney"]."元",'color'=>'#173177');
		$data['keyword2'] = array('value'=> "你发起的组团购已经完成订单，团长享受现金返还。",'color'=>'#173177');
		$data['keyword3'] = array('value'=> date('Y').'年'.date('m').'月'.date('d').'日 '.date('H').':'.date('i'),'color'=>'#173177');
		$data['remark'] = array('value'=> '返现将通过微信红包发送，请注意查收',"color"=>'#008000');

		$toUser = $order["fromUserName"];
		$template_id = $templateId;
		$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
			"&module=product&method=getOrderDetail&params=%7B%22id%22%3A%22$oid%22,%22tplid%22%3A1%7D";
		$url = urlencode($url);
		$topcolor = "#FF0000";
		//data得转json
		WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);

	}
}